package Servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import DAL.Entites.User;
import DAL.JDBC.DBConn;
import DAL.JDBC.UserJDBC;

public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    public Login() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		JSONObject loginResult = new JSONObject();
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		request.getSession().setAttribute("email", email);
		UserJDBC userJDBC = new UserJDBC(DBConn.getConnection());
		User user = userJDBC.getUserByEmail(email);
		try{
			if(user != null && password.equals(user.getPassword()))
			{
				loginResult.put("loginStatus", true);
			}
			else
			{
				loginResult.put("loginStatus", false);
				loginResult.put("message", "Email Or Password Incorrect");
			}
			
			PrintWriter pw = response.getWriter();
			pw.write(loginResult.toString());
		}
		catch(JSONException ex)
		{
			ex.printStackTrace();
		}
	}

}
